import { Injectable } from '@angular/core';
import {
  HttpEvent,
  HttpHandler,
  HttpInterceptor,
  HttpRequest,
  HttpResponse
} from '@angular/common/http';
import { Observable } from 'rxjs';
import { AuthService } from '../services/auth.service';
import { Router } from '@angular/router';
import { map } from 'rxjs/operators';

@Injectable()
export class AuthInterceptor implements HttpInterceptor {
  constructor(
    private readonly authService: AuthService,
    private readonly router: Router
  ) {}

  intercept(
    req: HttpRequest<any>,
    next: HttpHandler
  ): Observable<HttpEvent<any>> {
    const token = this.authService.fetchUserToken() || '';

    // 请求拦截，添加token
    const authReq = req.clone({
      setHeaders: { Authorization: token }
    });

    // 响应拦截，无效token转到登录界面
    return next.handle(authReq).pipe(
      map((res: any) => {
        if (res instanceof HttpResponse && res.status === 403) {
          this.router.navigate(['/auth']);
          throw 'invalid token';
        }
        return res;
      })
    );
  }
}
